from celery import Celery, current_task
import requests
import json

app = Celery(broker="{{ cookiecutter.celery_broker }}", backend="{{ cookiecutter.celery_backend }}")
app.conf.result_backend_transport_options = {'visibility_timeout': 18000}
app.conf.broker_transport_options = {'visibility_timeout': 18000}
STATUS_FINISHED = 0
STATUS_IN_PROGRESS = 1
STATUS_FAILED = 2
STATUS_NOT_START = 3
STATUS_STOPPING = 4
STATUS_STOPPED = 5

STATUS_ITEMS = (
    (STATUS_FINISHED, '处理完毕'),
    (STATUS_IN_PROGRESS, '正在处理'),
    (STATUS_FAILED, '异常'),
    (STATUS_NOT_START, '未处理'),
    (STATUS_STOPPING, '正在停止'),
    (STATUS_STOPPED, '已停止')
)


def fake_algorithm(input_params, extra_params):
    result = {
        "video_url": "http://192.168.202.90:9000/truck-video/3.mp4",
        "counts_url": "http://192.168.202.90:9000/trafficalg-bucket/video_19_10mins_counts.json"
    }
    return result


@app.task
def start_task(input_params, result_callback, progress_callback=None, extra_params=None):
    print('task_id: {current_task_id}'.format(current_task_id=current_task.request.id))
    result = fake_algorithm(input_params=input_params, extra_params=extra_params)

    # 如果有中间处理结果，将中间结果POST到progress_callback中
    # progress_dict = {
    #     # 字典内容需要和WEB应用协商确定
    # }
    # ret = requests.post(url=progress_callback,
    #                     data=json.dumps(progress_dict, ensure_ascii=False),
    #                     headers={'content-type': 'application/json'})

    result_dict = {
        "status": STATUS_FINISHED,
        "result": json.dumps(result, ensure_ascii=False)
    }
    # 如果处理成功，将处理结果PATCH到result_callback中
    ret = requests.patch(url=result_callback,
                         data=json.dumps(result_dict, ensure_ascii=False),
                         headers={'content-type': 'application/json'})
    # 如果处理失败
    # result_dict['status'] = STATUS_FAILED
    # ret = requests.patch(url=result_callback,
    #                      data=json.dumps(result_dict, ensure_ascii=False),
    #                      headers={'content-type': 'application/json'})

